package com.billdimmick.merkabah;

import junit.framework.Assert;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

public class TestMessageFormatAdapter {

	private static final Log log=LogFactory.getLog(TestMessageFormatAdapter.class);

	@Test
	public void testNoParameterAdapter() {
		final String body="Hello World";
		final MessageFormatAdapter original=MessageFormatAdapter.create(body);
		Assert.assertEquals(body, original.getBody());
		final MessageFormatAdapter parsed=MessageFormatAdapter.parse(original.toString());
		Assert.assertEquals(original.getBody(), parsed.getBody());
	}
	
	@Test
	public void testMessageFormatAdapter() {
		final String body="Hello World";
		final String [][] values={ {"encrypted", "false"}, {"nullvalue", null}, {"emptystring", ""} };

		//Part one - building it from scratch
		final MessageFormatAdapter original=MessageFormatAdapter.create(body);
		Assert.assertEquals(body, original.getBody());
		for (String [] pair: values) {
			original.setParameter(pair[0], pair[1]);
			Assert.assertEquals(pair[1], original.getParameter(pair[0]));
		}
		Assert.assertEquals(values.length, original.getKeys().size());
		
		//Part tow - building from a parsed message
		final MessageFormatAdapter parsed=MessageFormatAdapter.parse(original.toString());
		Assert.assertEquals(original.getBody(), parsed.getBody());		
		Assert.assertEquals(original.getKeys().size(), parsed.getKeys().size());
		for (String [] pair: values) {
			Assert.assertEquals(pair[1], parsed.getParameter(pair[0]));
		}		
		
		Assert.assertEquals(original, parsed);
	}
	
	@Test
	public void testEquality()  {
		final MessageFormatAdapter core1=MessageFormatAdapter.create("Hello");
		Assert.assertTrue(!core1.equals("something"));

		final MessageFormatAdapter core2=MessageFormatAdapter.create("Hello");
		final MessageFormatAdapter core3=MessageFormatAdapter.create("Goodbye");
		Assert.assertTrue(core1.equals(core2));
		Assert.assertTrue(!core1.equals(core3));
		core2.setParameter("foo", "bar");
		Assert.assertTrue(!core1.equals(core2));
		core1.setParameter("foo", "foo");
		Assert.assertTrue(!core1.equals(core2));
		core1.setParameter("foo", "bar");
		Assert.assertTrue(core1.equals(core2));
	}
	
	@Test
	public void testEdgeCases() {
		MessageFormatAdapter adapter=MessageFormatAdapter.create(null);
		Assert.assertNull(adapter.getBody());
		
		try {
			adapter=MessageFormatAdapter.parse(null);
			Assert.fail("Expected IllegalArgumentException");
		} catch (IllegalArgumentException iae) {}
		
		try {
			adapter.getParameter(null);
			Assert.fail("Expected IllegalArgumentException");
		} catch (IllegalArgumentException iae) {}
		
		try {
			adapter.setParameter(null, null);
			Assert.fail("Expected IllegalArgumentException");
		} catch (IllegalArgumentException iae) {}

		adapter.setParameter("null", null);

	}
}
